import { Button, Comment, Input, List, Space, Tooltip, message, Spin } from 'antd';
import { connect } from 'dva';
import { useState } from 'react';
import styles from './style.less'
import { save, deleteComment, pageComment } from '@/services/project/comment'
import { useEffect } from 'react';
import { parseDate, now } from '@/utils/dateUtils'
import TextButton from '@/components/TextButton'
import UserBrief from '@/components/UserBrief'

const CommentDetail = (props) => {

    const {
        comment,
        projectId,
        bizId,
        bizType,
        newCommentPosition,
        onSave,
        onCancel,
        onReply,
        level,
        brotherCommentMap
    } = props;

    const [subCommentMap, setSubCommentMap] = useState({})


    useEffect(() => {
        if (comment?.subComment) {
            let subCommentMap = []
            comment?.subComment.map(item => {
                subCommentMap[item.id] = item;
            })
            setSubCommentMap(subCommentMap);
        }
    }, [comment])



    return <Comment
        id={comment.id}
        className={styles.commentClass}
        actions={[<TextButton type="text" onClick={() => {
            onReply(comment)
        }} > 回复</TextButton>]}
        author={<UserBrief showAvatar={false} user={comment?.user}></UserBrief>}
        avatar={<UserBrief size="large" showName={false} user={comment?.user}></UserBrief>}
        content={<div>
            {comment.replyToId !== comment.parentId && (
                <div className={styles.replyToClassName}>
                    回复 {<UserBrief showAvatar={false} user={brotherCommentMap[comment.replyToId]?.user}></UserBrief>} : {' '}
                </div>
            )}
            {comment.content?.text}
        </div>}
        datetime={
            <Tooltip title={comment.createTime}>
                <span>{parseDate(comment.createTime).fromNow()}</span>
            </Tooltip>
        }
    >
        {newCommentPosition === comment.id && <CommentEdit
            parentId={level >= 3 ? comment.parentId : comment.id}
            replyToId={comment.id}
            replyToUser={comment.user}
            projectId={projectId}
            level={level}
            mainId={(comment.mainId && comment.mainId !== "0") ? comment.mainId : comment.id}
            bizId={bizId}
            bizType={bizType}
            onSave={onSave}
            onCancel={onCancel}></CommentEdit>}
        {comment.subComment && comment.subComment.map(item =>
            <CommentDetail
                key={item.id}
                comment={item}
                projectId={projectId}
                bizId={bizId}
                level={level + 1}
                bizType={bizType}
                onReply={onReply}
                onSave={onSave}
                onCancel={onCancel}
                brotherCommentMap={subCommentMap}
                newCommentPosition={newCommentPosition} >
            </CommentDetail>)}
    </Comment>
}

const CommentEdit = (props) => {

    const {
        onCancel,
        onSave,
        projectId,
        bizId,
        bizType,
        replyToId,
        replyToUser,
        parentId,
        mainId,
        level,
    } = props;

    const [commentContent, setCommentContent] = useState({});
    const [saveLoading, setSaveLoading] = useState();

    const onSaveComment = (comment) => {
        console.log(comment, comment?.content?.text)
        const text = comment?.content?.text;
        if (!text) {
            message.warning("评论内容为空")
            setSaveLoading(false)
            return;
        }
        if (text.length < 6) {
            message.warning("评论文字数需要大于6个")
            setSaveLoading(false)
            return;
        }
        save(projectId, bizType, bizId, comment).then((result) => {
            if (result?.success) {
                message.success("评论成功")
                setSaveLoading(false)
                if (onSave) {
                    onSave(result?.data)
                }
            }
        })
    }

    return <div className={styles.newCommentContentClass}>
        <Input.TextArea
            onChange={(e) => {
                setCommentContent({
                    text: e.target.value
                })
            }}
            autoSize={{ minRows: 3, maxRows: 6 }}
            placeholder={replyToUser ? '回复 ' + replyToUser.nickName : "请输入评论"}
            maxLength={249} showCount>
        </Input.TextArea>
        <Space style={{ marginTop: "4px" }}>
            <Button
                loading={saveLoading}
                onClick={() => {
                    if (onSave) {
                        setSaveLoading(true)
                        onSaveComment({
                            content: commentContent,
                            replyToId: replyToId,
                            parentId: parentId,
                            mainId: mainId
                        })
                    }
                }} type="primary">
                保存
             </Button>
            <Button onClick={() => {
                if (onCancel) {
                    onCancel()
                }
            }}>
                取消
        </Button>
        </Space>
    </div>
}


const ProjectComment = (props) => {

    const {
        projectId,
        bizId,
        bizType,
        myInfo
    } = props;

    const [newCommentPosition, setNewCommentPosition] = useState()
    const [commentList, setCommentList] = useState([])
    const [commentPageData, setCommentPageData] = useState();
    const [commentTotalCnt, setCommentTotalCnt] = useState(0)

    const [nextCommentPageLoading, setNextCommentPageLoading] = useState(false);

    useEffect(() => {
        if (bizId) {
            pageComment(projectId, bizType, bizId)
            .then((result) => {
                setCommentList([...(result?.data?.list || [])])
                setCommentPageData(result?.data);
                setCommentTotalCnt(result?.data?.count || 0)
            })
        }
       
    }, [bizId])


    const onCancel = () => {
        setNewCommentPosition()
    }

    const addToCommentList = (subCommentList, parentId, newComment) => {
        return subCommentList && subCommentList.map((item) => {
            if (item.id === parentId) {
                if (item.subComment) {
                    item.subComment = [newComment, ...item.subComment]
                } else {
                    item.subComment = [newComment]
                }
            } else {
                item.subComment = addToCommentList(item.subComment, parentId, newComment)
            }
            return { ...item };
        })
    }

    const onSave = (comment) => {
        setNewCommentPosition()
        let newComment = {
            user: myInfo,
            createTime: now(),
            ...comment
        }
        if (comment.parentId) {
            setCommentList(addToCommentList(commentList, comment.parentId, newComment))
        } else {
            setCommentTotalCnt(commentTotalCnt + 1)
            setCommentList([newComment, ...commentList])
            //滑动到指定位置
            // let anchorElement = document.getElementById(comment.id);
            // if (anchorElement) {
            //     anchorElement.scrollIntoView()
            // }
        }
    }

    const onLoadMore = () => {
        setNextCommentPageLoading(true)
        pageComment(projectId, bizType, bizId, {
            pageNum: commentPageData.pageNum + 1
        }).then((result) => {
            setCommentList([...commentList, ...result?.data?.list])
            setCommentPageData(result?.data)
            setNextCommentPageLoading(false)
        })
    }

    const onReply = (comment) => {
        setNewCommentPosition(comment.id)
    }

    const newCommentContent = newCommentPosition === "0" ?
        <CommentEdit projectId={projectId} bizId={bizId} bizType={bizType} onSave={onSave} onCancel={onCancel}></CommentEdit>
        :
        <Button type="primary" onClick={() => {
            setNewCommentPosition("0")
        }}>我要评论</Button>


    const loadMore =
        (!commentPageData) || commentPageData.pageNum >= commentPageData.totalPage ?
            '' :
            (<div
                style={{
                    textAlign: 'center',
                    marginTop: 8,
                    height: 24,
                    lineHeight: '24px',
                }}
            >
                {nextCommentPageLoading ? <Spin></Spin> :
                    <Button onClick={onLoadMore}>加载更多评论</Button>
                }

            </div>)

    return <>
        <div style={{ padding: "4px" }}>
            {newCommentContent}
            <div className={styles.commentCntClass}> 评论数：{commentTotalCnt} 条 </div>
        </div>
        <List
            className={styles.commentListClass}
            loading={!commentPageData}
            dataSource={commentList}
            loadMore={loadMore}
            locale={{
                emptyText: "暂无评论"
            }}
            renderItem={item => (
                <CommentDetail
                    comment={item}
                    level={1}
                    projectId={projectId}
                    bizId={bizId}
                    bizType={bizType}
                    onReply={onReply}
                    onSave={onSave}
                    onCancel={onCancel}
                    newCommentPosition={newCommentPosition}></CommentDetail>
            )}
        >
        </List>
    </>
}

export default connect(({ user }) => ({
    myInfo: user.myInfo
}))(ProjectComment)